#!/usr/bin/python

import os, sys
from xml.dom import minidom
from Tkinter import *
from random import randint
# start module and import iGIS variable (map home folder)
from connect import iGIS
from draw import draw

# choose random map
gisMap = os.listdir(iGIS)[randint(0, len(os.listdir(iGIS))) - 1]
print 'chosen map : ', iGIS + gisMap

gisMapParse = minidom.parse(iGIS + gisMap) # home folder -> chosen map
print 'OK - parse'

sizeOfMap = [] # x, y as strings
for i in gisMapParse.getElementsByTagName('map'):
  sizeOfMap.append(int(i.getAttribute('sizex')))
  sizeOfMap.append(int(i.getAttribute('sizey')))

# master window
master = Tk()
master.wm_title('iGIS')
# master canvas
w = Canvas(master, width=sizeOfMap[0], height=sizeOfMap[1], background='slate gray')
w.pack()

mapPoints = {}  # all points on the map {id:(x,y)}

for mapTag in gisMapParse.getElementsByTagName('map'):
  ### points
  for nodeTag in mapTag.getElementsByTagName('node'):
    point = (int(nodeTag.getAttribute('x')), int(nodeTag.getAttribute('y')))
    pointID = int(nodeTag.getAttribute('id'))
    mapPoints[pointID] = point

  # print all point coordinates
  print '... points ...'
  for k, v in mapPoints.iteritems():
    print k, ':', v   
  ### objects
  for objTag in mapTag.getElementsByTagName('object'):
    ### points of objects
    pointsOfObj = [] # id of first point of line
    for nodeTag in objTag.getElementsByTagName('nd'):
      pointsOfObj.append(int(nodeTag.getAttribute('ref')))
      print 'nd refs : ', nodeTag.getAttribute('ref')
    print 'points of object (IDs) : ', pointsOfObj
    # array for draw method
    points = []
    for p in pointsOfObj:
      points.append(mapPoints[p])
    ### type of object
    #for typeTag in objTag.getElementsByTagName('type'):
    #  objType = typeTag.getAttribute('t')
      
    ### object withour door rendering
    #if objType is None:
    #  draw(w, points)
    #else:
    #  draw(w, points, objType)
    ###
    draw(w, points)
    
    ### door rendering
    for doorTag in objTag.getElementsByTagName('door'):
      # if there is no door in object
      if doorTag is None:
        break
      doorPoints = []
      doorPoints.append(int(doorTag.getAttribute('ref1')))
      doorPoints.append(int(doorTag.getAttribute('ref2')))
      if len(doorPoints) is 2:
        print 'excellent door - 2 points'
        arr = []
        for dp in doorPoints:
          for mp in mapPoints[dp]:
            arr.append(mp)
        w.create_line(arr,
                      fill = 'black',
                      #dash = (4, 4),
                      width = 5.0)
      else:
        print 'strange door - not 2 points'
      print 'door points (IDs) : ', doorPoints
        
mainloop()

print 'goodbye, developper =)'
